from django.contrib import auth
from rest_framework.views import APIView
from rest_framework.response import Response
import logging
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from .models import GroupModel,GroupMembersModel,MessageModel
from datetime import datetime
from . serializers import MessageSerializer,GroupSerializer


class CsrfExemptSessionAuthentication(SessionAuthentication):
    def enforce_csrf(self, request):
        return


logger = logging.getLogger(__name__)


class StaticMessageView(APIView):
    authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)

    def get(self, request):
        context = dict()
        context['err_code'] = 0
        user = request.user
        if user.is_anonymous:
            context['err_code'] = 1001
            context['error'] = "您还未登录"
            return Response(context)
        group_name = request.GET.get('group')
        start = request.GET.get('start')
        if start is None or group_name is None:
            context['err_code'] = 3001
            context['error'] = "参数不正确"
            return Response(context)
        try:# 解析开始时间
            year = int(start[0: 4])
            mon = int(start[4: 6])
            day = int(start[6: 8])
            hour = int(start[8: 10])
            minute = int(start[10: 12])
            start = datetime(year=year, month=mon, day=day, hour=hour, minute=minute)
        except:
            context['err_code'] = 3001
            context['error'] = "参数不正确"
            return Response(context)
        group = GroupModel.objects.filter(name=group_name)  # 找到需要的组
        if not group.exists():
            context['err_code'] = 4004
            context['error'] = "消息组不存在"
            return Response(context)
        group = group.first()
        querys = GroupMembersModel.objects.filter(user=user, group=group)
        if not querys.exists() or querys.first().view == False:  # 无权限
            context['err_code'] = 4003
            context['error'] = "无权查看"
            return Response(context)
        end = request.GET.get('end')
        if end is None:# 没有结束时间，则只考虑开始时间
            querys = MessageModel.objects.filter(group=group,create_time__gt=start)
        else:
            try:
                year = int(end[0: 4])
                mon = int(end[4: 6])
                day = int(end[6: 8])
                hour = int(end[8: 10])
                minute = int(end[10: 12])
                end = datetime(year=year, month=mon, day=day, hour=hour, minute=minute)
            except:
                context['err_code'] = 3001
                context['error'] = "参数不正确"
                return Response(context)
            querys = MessageModel.objects.filter(group=group, create_time__gt=start,create_time__lt=end)
        querys = MessageSerializer(querys,many=True)
        context['data'] = querys.data
        return Response(context)
class TestView(APIView):
    authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)

    def get(self, request):
        import  json
        import time
        context = dict()
        context['err_code'] = 0
        from .dynamic import message_connections
        for con in message_connections:
            con.send(text_data=json.dumps({
                'message': "服务器主动发送消息"+time.strftime("%H-%M-%S")
            }))
        return Response(context)
class GroupView(APIView):
    authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)

    def get(self, request):
        context = dict()
        user = request.user
        if user.is_anonymous:
            context['err_code'] = 1001
            context['error'] = "您还未登录"
            return Response(context)
        data = GroupMembersModel.objects.filter(user=user,view=True)
        context['err_code'] = 0
        data = GroupSerializer(data,many=True).data
        context['data'] = data
        return Response(context)